package com.sip.stream.media;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.os.PowerManager;
import android.os.Process;
import android.os.SystemClock;
import android.util.Log;
import android.view.Surface;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.StringUtils;
import com.google.gson.Gson;
import com.sip.stream.ClientApp;
import com.sip.stream.R;
import com.sip.stream.activity.preview.IPreviewActivity;
import com.sip.stream.consumer.ZFYWavConsumer;
import com.sip.stream.rxbus.RxBus;
import com.sip.stream.utils.ImageSaver;
import com.sip.stream.utils.zfy.IGSNV12DataSource;
import com.sip.stream.utils.zfy.IGSWAVDataSource;
import com.sip.stream.utils.zfy.VideoEncryptUtils;
import com.sip.stream.utils.zfy.ZFYMediaInfo;
import com.sip.stream.utils.zfy.ZFYMediaUtil;
import com.sip.stream.utils.zfy.consumer.DSJGroupintercomConsumer;
import com.sip.stream.utils.zfy.consumer.IGSPlatformConsumer;
import com.sip.stream.utils.zfy.consumer.IGSVideoConsumer;
import com.sip.stream.utils.zfy.consumer.IPCPlatformConsumer;
import com.sip.stream.utils.zfy.consumer.ZFYMp4Consumer;
import com.sip.stream.utils.zfy.event.ZFYFileTransferEvent;
import com.sip.stream.utils.zfy.muxer.ZFYPreRecordConsumer;
import com.sip.stream.utils.zfy.voice.BeepTool;
import com.sip.stream.utils.zfy.ZFYFilePath;
import com.sip.stream.utils.zfy.config.ZFYMediaConfig;
import com.sip.stream.utils.zfy.config.ZFYOSDConfig;
import com.sip.stream.utils.zfy.encoder.IGSAudioEncoder;
import com.sip.stream.utils.zfy.encoder.IGSVideoEncoder;
import com.sip.stream.utils.zfy.encoder.ZFYEncoderFactory;
import com.sip.stream.utils.zfy.event.ZFYMediaEvent;
import com.sip.stream.utils.zfy.osd.OSDToolFactory;
import com.sip.stream.utils.zfy.proxy.PlatformProxy;
import com.sip.stream.utils.zfy.status.ZFYStatus;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.Single;
import io.reactivex.SingleEmitter;
import io.reactivex.SingleObserver;
import io.reactivex.SingleSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.BehaviorSubject;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class ZFYMediaManager {
    private static final String TAG = "ZFYMediaManager";

    public static final String ACTION_AI_PREVIEW = "aipreview";
    public static final String ACTION_AUDIO = "audio";
    public static final String ACTION_AUDIO_NOTE_START = "audio_note_start";
    public static final String ACTION_AUDIO_NOTE_STOP = "audio_note_stop";
    public static final String ACTION_AUDIO_START = "audio_start";
    public static final String ACTION_AUDIO_STOP = "audio_stop";
    public static final String ACTION_CAPTRUE = "captrue";
    public static final String ACTION_CAPTRUE_WITH_CONFIG = "captrue_config";
    public static final String ACTION_CHANGE_MEDIA_CONFIG_FROM_PLATFORM = "CHANGE_FROM_PLATFORM";
    public static final String ACTION_CHANGE_WIDE_ANGLE_DISTORTION = "WIDE_ANGLE_DISTORTION";
    public static final String ACTION_CHECK_AUDIO_MODE = "checkAudioMode";
    public static final String ACTION_GROUPINTERCOM = "groupintercom";
    public static final String ACTION_LAST_REPLAY = "last_replay";
    public static final String ACTION_MARK = "mark";
    public static final String ACTION_PRE_VIDEO = "pre_video";
    public static final String ACTION_REMOTE_AUDIO = "remoteAudio";
    public static final String ACTION_REMOTE_VIDEO = "remoteVideo";
    public static final String ACTION_RESET_PPI = "RESET_PPI";
    public static final String ACTION_START_FACE_DETECT = "START_FACE_DETECT";
    public static final String ACTION_START_QRSCAN = "START_QRSCAN";
    public static final String ACTION_STOP_FACE_DETECT = "STOP_FACE_DETECT";
    public static final String ACTION_STOP_QRSCAN = "STOP_QRSCAN";
    public static final String ACTION_SYNC_TIME = "syncTime";
    public static final String ACTION_USB_CHANGE = "ACTION_USB_CHANGE";
    public static final String ACTION_VIDEO = "video";
    public static final String ACTION_VIDEO_DELAY_STOP = "video_delay_stop";
    public static final String ACTION_VIDEO_START = "video_start";
    public static final String ACTION_VIDEO_STOP = "video_stop";
    public static final String CHANGE_MEDIA_CONFIG = "CHANGE_MEDIA_CONFIG";
    public static final String CHANGE_PPI = "CHANGE_PPI";
    public static final String KNOCK_PROTECT = "KNOCK_PROTECT";
    public static final String LEAVE_PREVIEW = "LEAVE_PREVIEW";
    public static final String PAUSE_PREVIEW = "PAUSE_PREVIEW";
    public static final String START_PREVIEW = "START_PREVIEW";
    public static final String VIDEO_PROTECT = "VIDEO_PROTECT";

    private static ZFYMediaManager instance;

    private Handler backgroundHandler;
    private HandlerThread backgroundThread;
    private SingleEmitter<Boolean> captureSubject;
    private ZFYMediaConfig config;
    private ZFYEncoderFactory encoderManager;
    private VideoEncryptUtils encryptUtils;
    private IPCPlatformConsumer ipcConsumer;
    private ZFYOSDConfig osdConfig;
    private IGSPlatformConsumer platformConsumer;
    private ZFYPreRecordConsumer preVideoConsumer;
    private ZFYMediaStatus status;
    private String stickyAction;
    private IGSVideoConsumer videoConsumer;
    private ZFYWavConsumer wavConsumer;
    private ZFYMediaUtil zfyMediaUtil = new ZFYMediaUtil();
    private ArrayList<ZFYMediaInfo> mediaInfos = new ArrayList<>();
    private final SimpleDateFormat FILEFORMAT = new SimpleDateFormat("yyyyMMddHHmmss");
    private Disposable watchStorageDisposable = null;
    private BehaviorSubject<Boolean> leaveActionSubject = null;
    private IGSNV12DataSource videoDataSource = null;
    private IGSNV12DataSource remoteVideoDataSource = null;

    public static ZFYMediaManager getInstance() {
        if (instance == null) {
            synchronized (ZFYMediaManager.class) {
                if (instance == null) {
                    instance = new ZFYMediaManager();
                }
            }
        }
        return instance;
    }

    private ZFYMediaManager() {
        Log.i(TAG, "create");
        this.status = new ZFYMediaStatus();
        readCacheConfig();
        HandlerThread handlerThread = new HandlerThread(TAG);
        this.backgroundThread = handlerThread;
        handlerThread.start();
        setUpHandler();
        setUpBus();
    }

    private void setUpHandler() {
        this.backgroundHandler = new Handler(this.backgroundThread.getLooper(), new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                return false;
            }
        });
    }

    private void setUpBus() {
        RxBus.getDefault().subscribe(this, "MEDIA_EVENT", AndroidSchedulers.from(this.backgroundHandler.getLooper()), new RxBus.Callback<ZFYMediaEvent>() {
            @Override
            public void onEvent(ZFYMediaEvent zFYMediaEvent) {
                Log.w(ZFYMediaManager.TAG, "RxBus " + zFYMediaEvent.getType() + " " + Process.myTid());
                String type = zFYMediaEvent.getType();
                if (type.equals("EVENT_TYPE_PLATFORM_START_VIDEO")){
                    //平台视频开始
                    ZFYMediaManager.this.handlerActionWithCheckForground(ACTION_REMOTE_VIDEO);
                }else if (type.equals("EVENT_TYPE_CHECK_STATUS_STOP_RECORDING")){
                    //检测状态停止录制
                    ZFYMediaManager.this.forceStopRecording();
                }else if (type.equals("EVENT_TYPE_BAT_IN")){
                    ZFYMediaManager.this.onBatin();
                }else if (type.equals("EVENT_TYPE_REMOTE_AUDIO_STOP")){
                    //远程音频停止
                    ZFYMediaManager.this.handlerActionWithCheckForground(ACTION_AUDIO_STOP);
                }else if (type.equals("EVENT_TYPE_PLATFORM_STOP_INVITE_VOICE_TALK")){
                    //停止语音对讲
                    BeepTool.play("VOIP_CALL_FINISHED", null);
                    ZFYMediaManager.this.getStatus().setRemoteInviteVoiceTalk(false);
                    RxBus.getDefault().post(new ZFYMediaEvent("EVENT_TYPE_CHECK_AUDIO_COMMUNICATION_MODE"), "MEDIA_EVENT");
                }else if (type.equals("EVENT_TYPE_STORAGE_ABNORMAL")){
                    //存储异常播报
                    BeepTool.play("STORAGE_ABNORMAL");
                }else if (type.equals("EVENT_TYPE_VIDEO_STOP_COMPLETE")){
                    //视频录制结束
                    BeepTool.play("VIDEO_STOP");
                    if (videoConsumer != null) {
                        videoConsumer = null;
                    }
                    getStatus().setBeginRecordingDate(null);
                }else if (type.equals("EVENT_TYPE_BAT_OUT")){
                    if (!getStatus().isVideoStart() || videoConsumer  == null) {
                        return;
                    }
                    videoConsumer.forceSwitchMuxer();
                    videoConsumer.switchBackup(true);
                }else if (type.equals("EVENT_TYPE_REMOTE_VIDEO_STOP")){
                    //远程视频停止
                    ZFYMediaManager.this.handlerActionWithCheckForground(ACTION_VIDEO_STOP);
                }else if (type.equals("EVENT_TYPE_REMOTE_AUDIO_START")){
                    //远程对讲开始
                    ZFYMediaManager.this.handlerActionWithCheckForground(ACTION_AUDIO_START);
                }else if (type.equals("EVENT_TYPE_PLATFORM_STOP")){
                    //平台调度停止
                    ZFYMediaManager.this.stopPlatformStream(true, true);
                }else if (type.equals("EVENT_TYPE_PLATFORM_INVITE_VOICE_TALK")){
                    //平台邀请语音通话
                    ZFYMediaManager.this.getStatus().setRemoteInviteVoiceTalk(true);
                    BeepTool.play("VOIP_CALL_CONNECTED", null);
                    RxBus.getDefault().post(new ZFYMediaEvent("EVENT_TYPE_CHECK_AUDIO_COMMUNICATION_MODE"), "MEDIA_EVENT");
                }else if (type.equals("EVENT_TYPE_GROUPINTERCOM_STOP_VIDEO")){
                    //停止视频会议
                    ZFYMediaManager.this.stopGroupintercomVideo();
                }else if (type.equals("EVENT_TYPE_REMOTE_VIDEO_START")){
                    //远程视频开始
                    ZFYMediaManager.this.handlerActionWithCheckForground(ACTION_VIDEO_START);
                }else if (type.equals("EVENT_TYPE_GROUPINTERCOM_START_VIDEO")){
                    //视频会议开始
                    ZFYMediaManager.this.handlerActionWithCheckForground("groupintercom");
                }else if (type.equals("EVENT_TYPE_REMOTE_CAPUTRE")){
                    //远程抓图
                    ZFYMediaManager.this.handlerActionWithCheckForground(ACTION_CAPTRUE);
                }else if (type.equals("EVENT_TYPE_PLATFORM_STOP_AUDIO")){
                    //平台停止音频
                    ZFYMediaManager.this.stopPlatformStream(false, false);
                }else if (type.equals("EVENT_TYPE_PLATFORM_STOP_VIDEO")){
                    //平台停止视频
                    ZFYMediaManager.this.stopPlatformStream(true, false);
                }else if (type.equals("EVENT_TYPE_PLATFORM_START_AUDIO")){
                    //平台开始音频
                    ZFYMediaManager.this.handlerActionWithCheckForground(ACTION_REMOTE_AUDIO);
                }
            }
        });
        //同步设备时间
        RxBus.getDefault().subscribe(this, "SYNC_DEV_TIME", new RxBus.Callback<Long>() {
            @Override
            public void onEvent(Long l) {
                ZFYMediaManager.this.syncDevTime(l.longValue());
            }
        });
    }

    public void onBackPreview(Context context) {

    }

    public void onLeavePreview() {
        Log.i(TAG, "onLeavePreview");
        if (encoderManager != null) {
            encoderManager.release();
        }
    }

    //读取媒体配置
    private void readCacheConfig() {
        if (this.config == null) {
            String configJson = SPUtils.getInstance().getString("MediaConfig", null);
            if (ObjectUtils.isEmpty(configJson)){
                this.config = new ZFYMediaConfig();
            }else{
                this.config = new Gson().fromJson(configJson,ZFYMediaConfig.class);
            }
        }
    }

    //保存媒体配置
    public void saveCacheConfig() {
        saveConfig(this.config);
    }
    public void saveConfig(ZFYMediaConfig zFYMediaConfig) {
        String json = new Gson().toJson(zFYMediaConfig);
        Log.i(TAG, "" + json);
        SPUtils.getInstance().put("MediaConfig",json);
    }

    //保存媒体配置参数
    public void changeConfig(ZFYMediaConfig zFYMediaConfig) {
        saveConfig(zFYMediaConfig);
        getStatus().getCameraParameters().setVideoHeight(zFYMediaConfig.getVideoHeight());
        getStatus().getCameraParameters().setVideoWidth(zFYMediaConfig.getVideoWidth());
        getStatus().getCameraParameters().setRemoteWidth(zFYMediaConfig.getStreamWidth());
        getStatus().getCameraParameters().setRemoteHeight(zFYMediaConfig.getStreamHeight());
    }

    public ZFYMediaConfig getConfig() {
        return this.config;
    }

    //读取OSD配置
    public ZFYOSDConfig getOSDConfig() {
        if (this.osdConfig == null)
        {
            String configJson = SPUtils.getInstance().getString(ZFYOSDConfig.SAVE_KEY, null);
            if (!StringUtils.isEmpty(configJson)) {
                this.osdConfig = new Gson().fromJson(configJson,ZFYOSDConfig.class);
            }
            if (this.osdConfig == null) {
                this.osdConfig = ZFYOSDConfig.defaultConfig();
            }
        }
        return this.osdConfig;
    }

    //保存OSD配置
    public void changeConfig(ZFYOSDConfig zFYOSDConfig) {
        String json = new Gson().toJson(zFYOSDConfig);
        SPUtils.getInstance().put(ZFYOSDConfig.SAVE_KEY,json);
    }

    public ZFYMediaStatus getStatus() {
        return this.status;
    }

    public ZFYCameraParameters getCameraParameters() {
        return this.status.getCameraParameters();
    }

    public Single<Boolean> startGroupintercomVideo(Single<IGSNV12DataSource> single, Single<IGSWAVDataSource> single2) {
        if (getStatus().isRemoteVideoAndAudio() || getStatus().isRemoteOnlyAudio()) {
            return Single.error(new Throwable("startGroupintercomVideo status error"));
        }
        getStatus().setGroupintercomVideo(true);
        return Single.zip(single2, single.map(new Function() {

            @Override
            public  Object apply(Object obj) {
                IGSNV12DataSource iGSNV12DataSource = (IGSNV12DataSource) obj;
                IGSVideoEncoder platformVideoEncoder = getEncoderManager().getPlatformVideoEncoder(iGSNV12DataSource.getWidth(), iGSNV12DataSource.getHeight(), iGSNV12DataSource.getFPS());
                iGSNV12DataSource.addConsumer(platformVideoEncoder);
                return platformVideoEncoder;
            }
        }), new BiFunction() {
            @Override
            public Object apply(Object obj, Object obj2) {
                IGSWAVDataSource iGSWAVDataSource = (IGSWAVDataSource) obj;
                IGSVideoEncoder iGSVideoEncoder = (IGSVideoEncoder) obj2;

                if (platformConsumer != null) {
                    platformConsumer.setVideoEncoder(iGSVideoEncoder);
                } else {
                    platformConsumer = new DSJGroupintercomConsumer();
                }
                iGSWAVDataSource.addConsumer(platformConsumer);
                return platformConsumer;
            }
        }).doOnSuccess(new Consumer() {
            @Override
            public void accept(Object obj) {
                RxBus.getDefault().post(new ZFYFileTransferEvent(ZFYFileTransferEvent.STOP_ALL), "FILETRANSFER_EVENT");
            }
        }).map(new Function() {
            @Override
            public Object apply(Object obj) {
                IGSPlatformConsumer iGSPlatformConsumer = (IGSPlatformConsumer) obj;
                iGSPlatformConsumer.start();
                platformConsumer = iGSPlatformConsumer;
                return Boolean.TRUE;
            }
        });
    }



    public synchronized void stopGroupintercomVideo() {
        Log.i(TAG, "stopGroupintercomVideo");
        if (getStatus().isGroupintercomVideo())
        {
            if (this.platformConsumer != null) {
                this.platformConsumer.stopVideo();
                this.platformConsumer = null;
            }
            getStatus().setGroupintercomVideo(false);
        }
    }

    private String getString(int resId) {
        return ClientApp.clientApp.getString(resId);
    }

    public synchronized Single<Boolean> stopVideoAction() {
        return Single.just(Boolean.TRUE).doOnSuccess(new Consumer() {
            @Override
            public  void accept(Object obj) {
                ZFYMediaManager.getInstance().getStatus().setVideoStart(false);
            }
        }).map(new Function() {
            @Override
            public Object apply(Object obj) {
                Log.i(TAG, "stopVideoAction mp4Consumer stop");
                if (videoConsumer != null) {
                    videoConsumer.stop();
                    return Boolean.TRUE;
                }
                return Boolean.FALSE;
            }
        }).doOnSuccess(new Consumer() {
            @Override
            public void accept(Object obj) {
                Boolean bool = (Boolean) obj;
                getStatus().setDlayRecording(false);
                getStatus().setBeginRecordingDate(null);
                videoConsumer = null;
                if (bool.booleanValue())
                {
                    BeepTool.play("VIDEO_STOP");
                    if (getInstance().getConfig().isTellRecordingTime()) {
                        BeepTool.playTime(getInstance().getStatus().getLastRecordingTime());
                    }
                    Single.timer(3L, TimeUnit.SECONDS).subscribe(new SingleObserver<Long>() {
                        @Override
                        public void onError(Throwable e) {
                            e.printStackTrace();
                        }

                        @Override
                        public void onSubscribe(Disposable disposable) {
                        }

                        @Override
                        public void onSuccess(Long l) {
                            //ZFYMediaCSVBinder.endAllMark(MyApplication.getInstance());
                        }
                    });
                }
                System.gc();
            }
        }).doOnError(new Consumer() {
            @Override
            public void accept(Object obj) {
                BeepTool.playString(getString(2131690538));
            }
        });
    }


    public synchronized Single<Boolean> startRemoteAudioAction(Single<IGSWAVDataSource> single) {
        return single.doOnSuccess(new Consumer() {
            @Override
            public  void accept(Object obj) {
                getStatus().setRemoteOnlyAudio(true);
            }
        }).map(new Function() {
            @Override
            public  Object apply(Object obj) {
                IGSWAVDataSource iGSWAVDataSource = (IGSWAVDataSource) obj;
                if (platformConsumer == null) {
                    platformConsumer = PlatformProxy.getInstance().createPlatformConsumer(null);
                    iGSWAVDataSource.addConsumer(platformConsumer);
                }
                platformConsumer.start();
                return Boolean.TRUE;
            }
        });
    }


    public synchronized Single startRemoteVideoAction(Single<IGSNV12DataSource> single, Single<IGSWAVDataSource> single2) {
        getStatus().setRemoteVideoAndAudio(true);
        return Single.zip(single2, single.map(new Function() {
            @Override
            public  Object apply(Object obj) {
                IGSNV12DataSource iGSNV12DataSource = (IGSNV12DataSource) obj;
                IGSVideoEncoder platformVideoEncoder = getEncoderManager().getPlatformVideoEncoder(iGSNV12DataSource.getWidth(), iGSNV12DataSource.getHeight(), iGSNV12DataSource.getFPS());
                iGSNV12DataSource.addConsumer(platformVideoEncoder);
                return platformVideoEncoder;
            }
        }), new BiFunction() {
            @Override
            public  Object apply(Object obj, Object obj2) {
                IGSWAVDataSource iGSWAVDataSource = (IGSWAVDataSource) obj;
                IGSVideoEncoder iGSVideoEncoder = (IGSVideoEncoder) obj2;

                if (ipcConsumer != null) {
                    ipcConsumer.setVideoEncoder(iGSVideoEncoder);
                    iGSWAVDataSource.addConsumer(ipcConsumer);
                    ipcConsumer = null;
                    return ipcConsumer;
                }

                if (platformConsumer != null) {
                    platformConsumer.setVideoEncoder(iGSVideoEncoder);
                    return platformConsumer;
                }
                IGSPlatformConsumer createPlatformConsumer = PlatformProxy.getInstance().createPlatformConsumer(iGSVideoEncoder);
                iGSWAVDataSource.addConsumer(createPlatformConsumer);
                return createPlatformConsumer;
            }
        }).map(new Function() {
            @Override
            public Object apply(Object obj) {
                IGSPlatformConsumer  iGSPlatformConsumer = (IGSPlatformConsumer) obj;
                iGSPlatformConsumer.start();
                platformConsumer = iGSPlatformConsumer;
                BeepTool.play("VIDEO_CALL_CONNECTED");
                if (getConfig().isAutoVideoWhenRemote() && !getStatus().isVideoStart()) {
                    getStatus().setIsAutoVideoWhenStream(true);
                    handlerActionWithCheckForground("video");
                }
                return Boolean.TRUE;
            }
        });
    }


    public Single<Boolean> stopPlatformVideoStreamActive() {
        if (!getStatus().isRemoteVideoAndAudio()) {
            return Single.just(Boolean.TRUE);
        }
        return Single.just(Boolean.TRUE).doOnSuccess(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean bool) throws Exception {
                if (ZFYMediaManager.this.getStatus().isRemoteVideoAndAudio()) {
                    if (ZFYMediaManager.this.platformConsumer != null) {
                        ZFYMediaManager.this.platformConsumer.stopVideo();
                    }
                    if (!ZFYMediaManager.this.getStatus().isRemoteOnlyAudio() && !ZFYMediaManager.this.getStatus().isRemoteVideoAndAudio()) {
                        ZFYMediaManager.this.platformConsumer = null;
                    }
                }
                ZFYMediaManager.this.getStatus().setRemoteVideoAndAudio(false);
                PlatformProxy.getInstance().stopVideoStreaming();
            }
        });
    }

    public synchronized void stopPlatformStream(boolean z, boolean z2) {
        if (z || z2)
        {
            if (getStatus().isRemoteVideoAndAudio()) {
                getStatus().setRemoteVideoAndAudio(false);
                BeepTool.play("VIDEO_CALL_FINISHED");
                if (getStatus().isAutoVideoWhenStream()) {
                    handlerActionWithCheckForground(ClientApp.clientApp, ACTION_VIDEO_STOP);
                }
                handlerActionWithCheckForground(ClientApp.clientApp, ACTION_RESET_PPI);
            } else {
                Log.w(TAG, "not need stopPlatformStream cause setRemoteVideoAndAudio false");
            }
        }
        if ((!z || z2) && getStatus().isRemoteOnlyAudio()) {
            Log.i(TAG, "setRemoteOnlyAudio false");
            getStatus().setRemoteOnlyAudio(false);
        }
        if ((z2 || z) && getStatus().isRemoteOnlyAudio() && this.platformConsumer != null) {
            this.platformConsumer.stopVideo();
        }
        if (!getStatus().isRemoteOnlyAudio() && !getStatus().isRemoteVideoAndAudio()) {
            if (this.platformConsumer != null) {
                this.platformConsumer.stop();
                this.platformConsumer = null;
            }
            PlatformProxy.getInstance().stopBusy();
        }
    }


    public synchronized Single<Boolean> stopPreVideoAction() {
        if (getStatus().isPreRecording() && this.preVideoConsumer != null) {
            return Single.just(Boolean.TRUE).map(new Function() {
                @Override
                public Object apply(Object obj) {
                    getStatus().setPreRecording(false);
                    BeepTool.play("PRE_RECORD_STOP");
                    if (preVideoConsumer != null) {
                        preVideoConsumer.stop();
                        preVideoConsumer = null;
                    }
                    return Boolean.TRUE;
                }
            });
        }
        getStatus().setPreRecording(false);
        return Single.just(Boolean.TRUE);
    }


    public synchronized Single<Boolean> startPreVideoAction(Single<IGSNV12DataSource> single, Single<IGSWAVDataSource> single2) {
        if (!checkDeviceStatus()) {
            return Single.error(new Exception("checkDeviceStatus error"));
        } else if (getStatus().isDelayRecording()) {
            return Single.error(new Exception(getString(R.string.preview_delay_recording)));
        } else {
            getStatus().setPreRecording(true);
            return Single.zip(Single.zip(single2, Single.just(getInstance().getEncoderManager().getMp4AudioEncoder()), new BiFunction() {
                @Override
                public  Object apply(Object obj, Object obj2) {
                    ((IGSWAVDataSource) obj).addConsumer((IGSAudioEncoder) obj2);
                    return Single.just(Boolean.TRUE);
                }
            }), Single.zip(single, Single.just(getInstance().getEncoderManager().getMp4VideoEncoder()), new BiFunction() {
                @Override
                public  Object apply(Object obj, Object obj2) {
                    ((IGSNV12DataSource) obj).addConsumer((IGSVideoEncoder) obj2);
                    return Single.just(Boolean.TRUE);
                }
            }), new BiFunction() {
                @Override
                public  Object apply(Object obj, Object obj2) {
                    IGSAudioEncoder iGSAudioEncoder = (IGSAudioEncoder) obj;
                    IGSVideoEncoder iGSVideoEncoder = (IGSVideoEncoder) obj2;
                    return new ZFYPreRecordConsumer(iGSVideoEncoder,iGSAudioEncoder);
                }
            }).doOnSuccess(new Consumer() {
                @Override
                public  void accept(Object obj) {
                    preVideoConsumer = (ZFYPreRecordConsumer) obj;
                }
            }).map(new Function() {
                @Override
                public  Object apply(Object obj) {
                    return Boolean.TRUE;
                }
            }).doOnSuccess(new Consumer() {
                @Override
                public  void accept(Object obj) {
                    Boolean bool = (Boolean) obj;
                    BeepTool.beepOneShot();
                }
            });
        }
    }


    public synchronized Single<Boolean> startVideoAction(Single<IGSNV12DataSource> igsnv12DataSourceSingle, Single<IGSWAVDataSource> igswavDataSourceSingle) {
        Single zip;
        if (!checkDeviceStatus()) {
            return Single.error(new Exception(getString(2131689658)));
        } else if (getStatus().isDelayRecording()) {
            return Single.error(new Exception(getString(2131690138)));
        } else {
            getStatus().setVideoStart(true);
            clearMarkInfos();
            if (this.preVideoConsumer != null) {
                zip = Single.just(this.preVideoConsumer).map(new Function() {
                    @Override
                    public Object apply(Object obj) {
                        return new ZFYMp4Consumer(preVideoConsumer);
                    }
                }).doFinally(new Action() {
                    @Override
                    public  void run() {
                        preVideoConsumer = null;
                        getStatus().setPreRecording(false);
                    }
                });
            } else {
                zip = Single.zip(Single.zip(igswavDataSourceSingle, Single.just(getInstance().getEncoderManager().getMp4AudioEncoder()), new BiFunction() {
                    @Override
                    public  Object apply(Object obj, Object obj2) {
                        ((IGSWAVDataSource) obj).addConsumer((IGSAudioEncoder) obj2);
                        return Single.just(Boolean.TRUE);
                    }
                }), Single.zip(igsnv12DataSourceSingle, Single.just(getInstance().getEncoderManager().getMp4VideoEncoder()), new BiFunction() {
                    @Override
                    public  Object apply(Object obj, Object obj2) {
                        ((IGSNV12DataSource) obj).addConsumer((IGSVideoEncoder) obj2);
                        return Single.just(Boolean.TRUE);
                    }
                }), new BiFunction() {
                    @Override
                    public  Object apply(Object obj, Object obj2) {
                        return new ZFYMp4Consumer((IGSVideoEncoder) obj2, (IGSAudioEncoder) obj);
                    }
                });
            }
            return zip.map(new Function() {
                @Override
                public  Object apply(Object obj) {
                    videoConsumer = (ZFYMp4Consumer) obj;
                    BeepTool.play("VIDEO_START");
                    return Boolean.TRUE;
                }
            }).doOnSuccess(new Consumer() {
                @Override
                public  void accept(Object obj) {
                    startWatchStorageAtTime();
                }
            });
        }
    }

    public Single<Boolean> markImportant() {
        return Single.just(Boolean.TRUE).doOnSuccess(new Consumer() {
            @Override
            public  void accept(Object obj) {
                BeepTool.play("MARKED");
                getStatus().setImportant(true);
                RxBus.getDefault().post(new ZFYMediaEvent("EVENT_TYPE_TIP", 2131690003), "MEDIA_EVENT");
            }
        });
    }

    public void switchMarkRecording() {
        if (!getStatus().isImportant()) {
            BeepTool.play("MARKED");
            getStatus().setImportant(true);
            RxBus.getDefault().post(new ZFYMediaEvent("EVENT_TYPE_TIP", 2131690003), "MEDIA_EVENT");
            return;
        }
        BeepTool.play("UNMARKED");
        getStatus().setImportant(false);
        RxBus.getDefault().post(new ZFYMediaEvent("EVENT_TYPE_TIP", 2131690014), "MEDIA_EVENT");
    }

    public synchronized Single<Boolean> stopAudioRecordAction() {
        return Single.just(Boolean.TRUE).map(new Function() {
            @Override
            public  Object apply(Object obj) {
                getStatus().setAudioStart(false);
                if (wavConsumer != null) {
                    wavConsumer.stop();
                    wavConsumer = null;
                    BeepTool.play("AUDIO_STOP");
                    if (getInstance().getConfig().isTellRecordingTime()) {
                        BeepTool.playTime(getInstance().getStatus().getLastRecordingTime());
                    }
                }
                return Boolean.TRUE;
            }
        });
    }


    public synchronized Single<Boolean> startAudioRecordAction(Single<IGSWAVDataSource> single) {
        if (!checkDeviceStatus()) {
            return Single.error(new Exception(getString(2131689658)));
        }
        return single.map(new Function() {
            @Override
            public  Object apply(Object obj) {
                IGSWAVDataSource iGSWAVDataSource = (IGSWAVDataSource) obj;
                getStatus().setAudioStart(true);
                ZFYWavConsumer zFYWavConsumer = new ZFYWavConsumer();
                iGSWAVDataSource.addConsumer(zFYWavConsumer);
                zFYWavConsumer.start();
                wavConsumer = zFYWavConsumer;
                return Boolean.TRUE;
            }
        }).doOnSuccess(new Consumer() {
            @Override
            public  void accept(Object obj) {
                BeepTool.play("AUDIO_START");
            }
        });
    }



    public void captureTimer() {
        handlerActionWithCheckForground(ACTION_CAPTRUE);
    }

    public ArrayList<ZFYMediaInfo> getInMarkMediaInfos() {
        return this.mediaInfos;
    }

    public void clearMarkInfos() {
        Log.i(TAG, "clearMarkInfos");
        this.mediaInfos.clear();
    }

    public ZFYMediaInfo createNewRecording(int i) {
        ZFYMediaInfo zFYMediaInfo = new ZFYMediaInfo();
        String str = getNewFileName() + (i == 2 ? ".tempwav" : ".tempmp4");
        String newFullPath = this.zfyMediaUtil.getNewFullPath(str);
        zFYMediaInfo.setFilename(str);
        zFYMediaInfo.setFilepath(newFullPath);
        zFYMediaInfo.setFiletype(i);
        zFYMediaInfo.setCreatedate(new Date());
        this.mediaInfos.add(zFYMediaInfo);
        return zFYMediaInfo;
    }

    public ZFYMediaInfo createNewYUVRecording() {
        ZFYMediaInfo zFYMediaInfo = new ZFYMediaInfo();
        String str = getNewFileName() + ".tempyuv";
        String newFullPath = this.zfyMediaUtil.getNewFullPath(str);
        zFYMediaInfo.setFilename(str);
        zFYMediaInfo.setFilepath(newFullPath);
        zFYMediaInfo.setFiletype(1);
        zFYMediaInfo.setCreatedate(new Date());
        return zFYMediaInfo;
    }

    public String getNewFileName() {
        return this.zfyMediaUtil.getNewFileName();
    }

    public synchronized long getPresentationTimeUs() {
        return SystemClock.elapsedRealtimeNanos() / 1000;
    }

    public void startCapture(SingleEmitter<Boolean> singleEmitter) {
        if (this.captureSubject != null) {
            singleEmitter.onError(new Throwable(getString(2131689501)));
        } else {
            this.captureSubject = singleEmitter;
        }
    }

    public void onCaptureComplete(byte[] bArr, int i,  int i2,  int i3) {
        Single error;
        if (i == 256) {
            error = Single.just(bArr).observeOn(Schedulers.newThread()).map(new Function() {
                @Override
                public  Object apply(Object obj) {
                    String saveJPEGImage = "";
                    //saveJPEGImage = new ImageSaver().saveJPEGImage((byte[]) obj);
                    return saveJPEGImage;
                }
            });
        } else if (i == 17) {
            error = Single.just(bArr).observeOn(Schedulers.newThread()).map(new Function() {
                @Override
                public Object apply(Object obj) {
                    if (OSDToolFactory.createOSDTool(i, i2, getOSDConfig()).addOSDCache(bArr)) {
                        return new ImageSaver().saveImage(bArr, i, i2);
                    }
                    return obj;
                }
            });
        } else {
            error = Single.error(new Throwable("cann't save cause unknown format"));
        }
        error.map(new Function() {
            @Override
            public  Object apply(Object obj) {
                return Log.i(ZFYMediaManager.TAG, "capture success " + ((String) obj));
            }
        }).subscribe(new SingleObserver<Boolean>() {
            @Override
            public void onSubscribe(Disposable disposable) {
            }

            @Override
            public void onSuccess(Boolean bool) {
                if (ZFYMediaManager.this.captureSubject != null) {
                    ZFYMediaManager.this.captureSubject.onSuccess(Boolean.TRUE);
                    ZFYMediaManager.this.captureSubject = null;
                }
            }

            @Override
            public void onError(Throwable th) {
                if (ZFYMediaManager.this.captureSubject != null) {
                    ZFYMediaManager.this.captureSubject.onError(th);
                    ZFYMediaManager.this.captureSubject = null;
                }
            }
        });
    }

    public ZFYEncoderFactory getEncoderManager() {
        if (this.encoderManager == null) {
            this.encoderManager = new ZFYEncoderFactory();
        }
        return this.encoderManager;
    }

    public void forceStopRecording() {
        if (getStatus().isVideoStart()) {
            stopVideoAction().subscribe(new Consumer() {
                @Override
                public void accept(Object obj) {
                }
            });
        } else if (getStatus().isAudioStart()) {
            stopVideoAction().subscribe(new Consumer() {
                @Override
                public  void accept(Object obj) {
                }
            });
        }
        if (this.videoConsumer != null) {
            this.videoConsumer.stop(true);
            this.videoConsumer = null;
        }
    }

    public Single<Boolean> checkCanStartMedia() {
        if (ZFYStatus.getInstance().getBatteryLevel() <= 2) {
            BeepTool.play("LOW_BATTERY");
            return Single.error(new Throwable(getString(2131689974)));
        } else if (!ZFYFilePath.getInstance().checkCardStatus()) {
            BeepTool.play("STORAGE_ABNORMAL");
            return Single.error(new Throwable(getString(2131689975)));
        } else if (ZFYStatus.getInstance().isStorageAbnormal()) {
            BeepTool.play("STORAGE_ABNORMAL");
            return Single.error(new Throwable(getString(2131689975)));
        } else if (ZFYFilePath.getInstance().isStorageFull()) {
            BeepTool.play("STORAGE_FULL");
            return Single.error(new Throwable(getString(2131689658)));
        } else {
            return Single.just(Boolean.TRUE);
        }
    }

    public boolean checkDeviceStatus() {
        if (ZFYStatus.getInstance().getBatteryLevel() <= 2) {
            BeepTool.play("LOW_BATTERY");
            RxBus.getDefault().post(new ZFYMediaEvent("EVENT_TYPE_ERROR", 2131689974), "MEDIA_EVENT");
            return false;
        } else if (!ZFYFilePath.getInstance().checkCardStatus()) {
            BeepTool.play("STORAGE_ABNORMAL");
            RxBus.getDefault().post(new ZFYMediaEvent("EVENT_TYPE_ERROR", 2131689975), "MEDIA_EVENT");
            return false;
        } else if (ZFYStatus.getInstance().isStorageAbnormal()) {
            BeepTool.play("STORAGE_ABNORMAL");
            RxBus.getDefault().post(new ZFYMediaEvent("EVENT_TYPE_ERROR", 2131689975), "MEDIA_EVENT");
            return false;
        } else if (ZFYFilePath.getInstance().isStorageFull()) {
            Log.i(TAG, "ZFYFilePath.getInstance().isStorageFull()");
            PlatformProxy.getInstance().postAlarmTypeToPlatform("Storage", "STORAGE_FULL");
            BeepTool.play("STORAGE_FULL");
            RxBus.getDefault().post(new ZFYMediaEvent("EVENT_TYPE_ERROR", 2131689658), "MEDIA_EVENT");
            return false;
        } else {
            return true;
        }
    }

    private synchronized void startWatchStorageAtTime() {
        stopWatchStorageAtTime();
        Observable.interval(1L, TimeUnit.MINUTES).subscribeOn(Schedulers.single()).subscribe(new Observer<Long>() {
            @Override
            public void onComplete() {
            }

            @Override
            public void onError(Throwable th) {
            }

            @Override
            public void onSubscribe(Disposable disposable) {
                ZFYMediaManager.this.watchStorageDisposable = disposable;
            }

            @Override
            public void onNext(Long l) {
                if (ZFYMediaManager.this.checkDeviceStatus()) {
                    return;
                }
                ZFYMediaManager.this.forceStopRecording();
            }
        });
    }

    private synchronized void stopWatchStorageAtTime() {
        Disposable disposable = this.watchStorageDisposable;
        if (disposable != null) {
            disposable.dispose();
            this.watchStorageDisposable = null;
            Log.i(TAG, "checkDeviceStatus watchStorageAtTime stop");
        }
    }

    public boolean forceStop() {
        Log.i(TAG, "forceStop: " + getStatus().toString());
        if (getStatus().isRemoteVideoAndAudio() || getStatus().isRemoteOnlyAudio()) {
            Log.i(TAG, "PlatformProxy stopStreaming");
            PlatformProxy.getInstance().stopStreaming();
        }
        stopWatchStorageAtTime();
        ArrayList arrayList = new ArrayList();
        arrayList.add(stopPreVideoAction());
        arrayList.add(stopVideoAction());
        arrayList.add(stopAudioRecordAction());
        Single.zip(arrayList, new Function() {
            @Override
            public  Object apply(Object obj) {
                return Boolean.TRUE;
            }
        }).subscribe(new SingleObserver<Boolean>() {
            @Override
            public void onError(Throwable th) {
            }

            @Override
            public void onSubscribe(Disposable disposable) {
            }

            @Override
            public void onSuccess(Boolean bool) {
            }
        });
        return true;
    }

    public String getStickyAction() {
        return this.stickyAction;
    }

    public void setStickyAction(String stickyAction) {
        this.stickyAction = stickyAction;
    }


    public void onBatin() {
        if (getStatus().isVideoStart()) {
            IGSVideoConsumer iGSVideoConsumer = this.videoConsumer;
            if (iGSVideoConsumer != null) {
                iGSVideoConsumer.switchBackup(false);
            }
            FileUtils.deleteFilesInDir(ZFYFilePath.getBarstreamBackupPath());
        }
    }

    public BehaviorSubject<Boolean> getLeaveActionSubject() {
        return this.leaveActionSubject;
    }

    public synchronized Single<Boolean> leaveAction() {
        if (!(ActivityUtils.getActivityList().size() > 0)) {
            return Single.just(Boolean.TRUE);
        }
        Activity currentActivity = ActivityUtils.getTopActivity();
        if (!(currentActivity instanceof IPreviewActivity))
        {
            Log.i(TAG, "not IPreviewActivity");
            return Single.just(Boolean.TRUE);
        } else if (this.leaveActionSubject != null) {
            Log.i(TAG, "leaveActionSubject != null");
            return this.leaveActionSubject.firstOrError().doFinally(new Action() {
                @Override
                public  void run() {
                    Log.i(TAG, "twice doFinally leaveActionSubject = null");
                    leaveActionSubject = null;
                }
            });
        } else {
            this.leaveActionSubject = BehaviorSubject.create();
            Log.i(TAG, "handleMediaAction LEAVE_PREVIEW " + currentActivity);
            ((IPreviewActivity) currentActivity).handleMediaAction("LEAVE_PREVIEW");
            return this.leaveActionSubject.firstOrError().timeout(10L, TimeUnit.SECONDS, Single.just(Boolean.FALSE)).doFinally(new Action() {
                @Override
                public void run() {
                    Log.i(TAG, "doFinally leaveActionSubject = null");
                    leaveActionSubject = null;
                }
            });
        }
    }


    public void handlerActionWithCheckForground(String str) {
        handlerActionWithCheckForground(ClientApp.clientApp, str);
    }

    public void handlerActionOnlyForground(String str) {
        if (ActivityUtils.getActivityList().size() > 0)
        {
            Activity currentActivity = ActivityUtils.getTopActivity();
            if (currentActivity instanceof IPreviewActivity)
            {
                IPreviewActivity iPreviewActivity = (IPreviewActivity) currentActivity;
                if (iPreviewActivity.isOpenedCamera())
                {
                    iPreviewActivity.handleMediaAction(str);
                }
            }
        }
    }

    public void handlerActionWithCheckForground(Context context, String stickyAction) {

    }

    SingleSource m466x41b7bb26(Boolean bool) throws Exception {
        Activity currentActivity = ActivityUtils.getTopActivity();
        Log.d(TAG, "activity " + currentActivity.getLocalClassName());
        if (currentActivity instanceof IPreviewActivity) {
            Log.d(TAG, "activity instanceof IPreviewActivity");
            return ((IPreviewActivity) currentActivity).backToPreview();
        }
        if (!ZFYStatus.getInstance().isScreenOn()) {
            wakeScreen();
        }
        Intent intent = new Intent("com.gosuncn.android.recorder.startPreview");
        intent.addCategory("android.intent.category.DEFAULT");
        ActivityUtils.startActivity(intent);
        return Single.just(Boolean.TRUE).delay(200L, TimeUnit.MILLISECONDS);
    }

    static  Boolean lambda$handlerActionWithCheckForground$47(String str) throws Exception {
        Activity currentActivity = ActivityUtils.getTopActivity();
        if (currentActivity instanceof IPreviewActivity) {
            Log.i(TAG, "handleMediaAction " + str);
            ((IPreviewActivity) currentActivity).handleMediaAction(str);
        }
        Log.i(TAG, "not IPreviewActivity");
        return Boolean.TRUE;
    }

    public Single<String> checkNeedWakeScreen(String str) {
        return Single.just(str).flatMap(new Function() {
            @Override
            public  Object apply(Object obj) {
                return "";
            }
        });
    }


    public void wakeScreen() {

    }

    public boolean syncDevTime(long j) {
        syncDevTimeAction(j).subscribe(new SingleObserver<Boolean>() {
            @Override
            public void onError(Throwable th) {
            }

            @Override
            public void onSubscribe(Disposable disposable) {
            }

            @Override
            public void onSuccess(Boolean bool) {
            }
        });
        return Boolean.TRUE.booleanValue();
    }

    public Single<Boolean> cacheSyncDevTime() {
        return syncDevTimeAction(System.currentTimeMillis() - getStatus().getSyncTime());
    }

    public Single<Boolean> syncDevTimeAction(long j) {
        return Single.just(Boolean.FALSE).delay(1L, TimeUnit.SECONDS);
    }


    public boolean isNeedAudioStream() {
        return getInstance().getStatus().isVideoStart() || getInstance().getStatus().isAudioStart() || getInstance().getStatus().isPreRecording() || getInstance().getStatus().isDelayRecording() || getInstance().getStatus().isRemoteVideoAndAudio() || getInstance().getStatus().isRemoteOnlyAudio() || getInstance().getStatus().isGroupintercomVideo();
    }

    public boolean isNeedVideoStream() {
        return getInstance().getStatus().isVideoStart() || getInstance().getStatus().isPreRecording() || getInstance().getStatus().isDelayRecording() || getInstance().getStatus().isQrscan() || (!getConfig().isDualStream() && getInstance().getStatus().isRemoteVideoAndAudio());
    }

    public boolean isNeedRemoteStream() {
        return (getInstance().getConfig().isDualStream() && getInstance().getStatus().isRemoteVideoAndAudio()) || getInstance().getStatus().isGroupintercomVideo();
    }

    public void forceSwitchVideo() {
        if (getStatus().isVideoStart()) {
            IGSVideoConsumer iGSVideoConsumer = this.videoConsumer;
            if (iGSVideoConsumer != null) {
                iGSVideoConsumer.forceSwitchMuxer();
            }
            BeepTool.beepOneShot();
            return;
        }
        RxBus.getDefault().post(new ZFYMediaEvent("EVENT_TYPE_REMOTE_VIDEO_START"), "MEDIA_EVENT");
    }

    public void changeConfigPlatform(String str) {
        Log.i(TAG, "changeConfigPlatform " + str);
        StringUtils.isEmpty(str);
    }


    public void setRemotePerformanceLevel(int i) {
        if (this.encoderManager != null) {
            Log.i(TAG, "setRemotePerformanceLe vel " + i);
            this.encoderManager.setRemotePerformanceLevel(i);
        }
    }

    public void startIPCVideo(Surface surface) {
        IPCPlatformConsumer iPCPlatformConsumer = new IPCPlatformConsumer();
        this.ipcConsumer = iPCPlatformConsumer;
        iPCPlatformConsumer.setUp(surface);
        getInstance().handlerActionWithCheckForground("remoteVideo");
    }

    private VideoEncryptUtils getEncryptUtils() {
        if (this.encryptUtils == null) {
            this.encryptUtils = new VideoEncryptUtils();
        }
        return this.encryptUtils;
    }

    public void setVideoDataSource(IGSNV12DataSource iGSNV12DataSource) {
        this.videoDataSource = iGSNV12DataSource;
    }

    public IGSNV12DataSource getVideoDataSource() {
        return this.videoDataSource;
    }

    public void setRemoteVideoDataSource(IGSNV12DataSource iGSNV12DataSource) {
        this.remoteVideoDataSource = iGSNV12DataSource;
    }

    public IGSNV12DataSource getRemoteVideoDataSource() {
        return this.remoteVideoDataSource;
    }
}
